/*
 * @Author: 肖思汗 
 * @Date: 2020-08-25 00:33:47 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-05-09 12:58:08
 */

import emiter, { emit } from "@emiter";
import cuid from "cuid";

export default class mixin_emiter extends emit {

    constructor() {
        super();
    }

    id = cuid();

    // 记录的此对象上上的 事件名和 回调
    callbacks: Array<{ eventName: string, callback: (...args: any[]) => void }> = [];

    // 分发事件
    emit(eventName: string, ...arg: any) {
        emiter.emit(eventName, arg);
        return false;
    }

    // 添加监听
    on(eventName: string, callback: (...args: any[]) => void) {

        // 先取消一次避免重复监听
        emiter.off(eventName, callback);
        // 添加监听事件
        emiter.on(eventName, callback);
        // 记录监听事件方便组件卸载时取消
        this.callbacks.push({ eventName, callback });
        return this;
    }

    // 添加一次性的监听
    once(eventName: string, callback: (...args: any[]) => void) {

        // 添加监听事件
        emiter.once(eventName, callback);
        this.callbacks.push({ eventName, callback });
        return this;
    }

    // 取消监听
    off(eventName: string, callback: (...args: any[]) => void) {

        emiter.off(eventName, callback);
        return this;
    }

    // 移除此对象上记录的所有监听
    removeAll() {

        this.callbacks.map(call => {
            emiter.off(call.eventName, call.callback);
        });
    }
}